import cv2
import sys
from collections import Counter

from libs.algorithm import RecognitionAlgorithm
from libs.ioctrl import IoCtrl

'''
答题卡计数专用类，组织相关代码到此类下
'''
class ImageCounter:

    '''
    获取图像
    '''
    @staticmethod
    def capture():

        #补光灯开启
        IoCtrl.fillLightWithDelay()

        cap = cv2.VideoCapture(0)
        width = 1900       # 长度 UI界面
        height =1500       # 高度 UI界面
        cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
        cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
        cap.set(cv2.CAP_PROP_FOURCC,cv2.VideoWriter.fourcc("M","J","P","G"))
        ret,frame = cap.read()
        cap.release()
        return frame

    '''
    解析图像,返回从图像中得到的张数
    '''
    @staticmethod
    def analysis(frame):
        plist = [None] * 6

        Appro_Num=35

        for i in range (1,5):
            r1=240*i
            r2=240*i+4
            r3=600                          # 变量 左取景框边界值
            r4=1605                         # 变量 右取景框边界值
            I20 = cv2.cvtColor(frame[r1:r2,r3:r4,:], cv2.COLOR_BGR2GRAY)
            sum_I0=RecognitionAlgorithm.sum_col(I20)
            sum_I20=RecognitionAlgorithm.filter_G(sum_I0)
            diff_I20=RecognitionAlgorithm.diff_fb(sum_I20)
            pp=RecognitionAlgorithm.p_count(diff_I20,Appro_Num)
            # locals 在函数内不支持动态变量了
            # https://blog.csdn.net/qq_35492650/article/details/89736049
            #locals()["p"+str(i)]=pp
            plist[i] = pp
        
        p90=[plist[1][2], plist[1][3], plist[2][2], plist[2][3], plist[3][2], plist[3][3], plist[4][2], plist[4][3]]
        p91=Counter(p90).most_common(1)[0][0]
        p92=Counter(plist[1]+plist[2]+plist[3]+plist[4]).most_common(1)[0][0]

        # 计算得出的纸张张数
        pageCount = 0
        if p91==p92:
            pageCount=p92
        else:
            pageCount=p91
        return pageCount

    '''
        调用拍照并且解析-返回结果
    '''
    @staticmethod
    def capAndAnalysis():
        frame = ImageCounter.capture()
        return ImageCounter.analysis(frame)